<?php

class PostController extends AppController
{
    var $uses = array("Post", "Track", "Site", "Embed", "Photo", "Like", "Artist", "Event", "Tag", "Object_tag", "User", "Track_artist");
    var $components = array("Session");
    
    function latest($page = 1)
    {
        $tracks = $this->Track->findAll(null, null, "`Post`.`date` DESC", 25, $page);
		$total_results = $this->Track->findCount(null);
        $this->setPlaylist($tracks);

        $tracks = self::_getEmbeds($tracks);
        $tracks = self::_getPhotos($tracks);
        $player = self::player($page);
        
        $artists = $this->Track->getPopularArtists();
        $djs = $this->Track->getPopularDJs();
        $tags = $this->Tag->getPopularTags();
        $this->set('artists', $artists);
        $this->set('djs', $djs);
        $this->set('page', $page);
        $this->set('tracks', $tracks);
		$this->set('total_results', $total_results);
        $this->set('tags', $tags);
        $this->set('player', $player);
        $this->set('page_title', 'The Latest Blogged MP3s');
    }

    function tag($tag, $page = 1)
    {
        $tracks = $this->Track->findByTag(low($tag), "`Post`.`date` DESC", 25, $page);
        $this->setPlaylist($tracks);

        $tracks = self::_getEmbeds($tracks);
        $tracks = self::_getPhotos($tracks);
             
        $player = self::player($page);
        
        $this->set('artists', $artists);
        $this->set('djs', $djs);
        $this->set('page', $page);
        $this->set('tracks', $tracks);
        $this->set('player', $player);
        $this->set('page_title', 'Tag: '.$tag);
        
        $tag_artists = $this->Artist->Tag->findAll(array("Tag.tag" => $tag), null, null, 10);

        $this->set('tag_artists', $tag_artists[0]);
        
        $this->render('latest');
    }
    
    function setPlaylist($tracks)
    {
        $this->Session->start();
        $this->Session->write('tracks', $tracks);
    }
    
    function xml()
    {
        $this->Session->start();
        $tracks = $this->Session->read('tracks');
        $xml = new DomDocument();        
        $root = $xml->createElement('xml');
        
        foreach ($tracks as &$track)
        {
            $track_tag = $xml->createElement('track');

            if ($track['Track']['cdn_domain']) $path = $xml->createElement('path', $track['Track']['cdn_domain'].$track['Track']['cdn_path']);
            else $path = $xml->createElement('path', $track['Track']['url']);
            
            $title = $xml->createElement('title', ucwords($track['Track']['name']));
            $track_tag->appendChild($path);
            $track_tag->appendChild($title);
            $root->appendChild($track_tag);
            
        }
        $xml->appendChild($root);
        echo $xml->saveXML();
        exit;     
    }
  
    function playlist()
    {
        $this->Session->start();
        $tracks = $this->Session->read('tracks');

        $xml = new DomDocument();        
        $root = $xml->createElement('playlist');      
        $tracklist = $xml->createElement('trackList');
        
        foreach ($tracks as &$track)
        {
            //$track = $this->Track->format($track);
            $track_tag = $xml->createElement('track');
            
            if ($track['Track']['cdn_domain']) $path = $xml->createElement('location', $track['Track']['cdn_domain'].$track['Track']['cdn_path']);
            else $path = $xml->createElement('location', "/tracks/".$track['Track']['id'].'.mp3');
            
            $title = $xml->createElement('title', ucwords($track['Track']['name']));
            $track_tag->appendChild($path);
            $track_tag->appendChild($title);
            $tracklist->appendChild($track_tag);
            
        }
        
        $root->appendChild($tracklist);
        $xml->appendChild($root);
        echo $xml->saveXML();
        exit;     
    }  
    
    function artist($artist, $page = 1)
    {
        $photo = $this->Photo->find(array('object_type' => 'artist', 'object_key' => $tracks[0]['Track']['artist_id']), null, 'Photo.id DESC');
        
        if ($photo['Photo']['id'])
        {
            $this->set('image', '<img style="width: 160px" src="/img/artist/'.$photo['Photo']['id'].'.jpg" />');
        }
       

        $artist = $this->Artist->find(array('Artist.name' => $artist));
        $artist_id = $artist['Artist']['id'];

        $tracks_raw = $this->Track->query(
		"(SELECT Track.id FROM tracks as Track 
		JOIN posts as Post ON Track.post_id = Post.id
		WHERE Track.artist_id = $artist_id)

		UNION 

		(SELECT Track.id FROM tracks as Track
		JOIN posts as Post ON Track.post_id = Post.id
		JOIN track_artists as Track_artist ON Track_artist.artist_id = $artist_id
		AND Track.id = Track_artist.track_id
		)");
		
		$track_ids = array();
		
		foreach ($tracks_raw as $track)
		{
			$track_ids[] = $track[0]['id'];
		}

		$total_results = count($track_ids);     
        $this->setPlaylist($tracks);
		$player = self::player($page);
		
		$tracks = $this->Track->findAll("Track.id IN (".implode(",", $track_ids).")", null, "Post.date DESC", null, $page);
		
        $this->set('events', $events);
        $this->set('artist', $artist);
        $this->set('h1', $artist);
        $this->set('page', $page);
        $this->set('tracks', $tracks);
		$this->set('total_results', $total_results);
        $this->set('player', $player);
		$this->set('extra_page_arg', $artist['Artist']['name']);
        $this->set('page_title', 'Songs by '.ucwords($artist['Artist']['name']));
        $this->render('latest');
    }
    
    function home($username, $page = 1)
    {
        $this->Session->start();
        $user = $this->User->find(array("User.username" => $username));
        $tracks = $this->Like->findAll(array('Like.user_id' => $user['User']['id']), null, "`Like`.`date` DESC", 25, $page);
		$total_results = $this->Like->findCount(array('Like.user_id' => $user['User']['id']));
		
        $tracks = self::_getEmbeds($tracks);
        $this->setPlaylist($tracks);

        $player = self::player($page);

        if ($photo = $this->Photo->find(array('object_type' => 'artist', 'object_key' => $tracks[0]['Track']['artist_id']), null, 'Photo.id DESC'))
        {
            $this->set('image', '<img style="width: 160px" src="/img/artist/'.$photo['Photo']['id'].'.jpg" />');
        
        }
        
        file_get_contents('http://mp3.sonicportal.net/get_artist_images.php?id='.$tracks[0]['Track']['artist_id']);

        $events = $this->Event->findAll(array('artist_id' => $tracks[0]['Track']['artist_id']), null, 'Event.date DESC');
        $artist = $this->Artist->find(array('Artist.name' => $artist));
        
        $tracks[0]['Post']['id'] = 1;
        
        $this->set('events', $events);
        $this->set('artist', $artist);
        $this->set('h1', $artist);
        $this->set('page', $page);
        $this->set('tracks', $tracks);
		$this->set('total_results', $total_results);
        $this->set('player', $player);
		$this->set('extra_page_arg', $username);
        $this->set('page_title', $username."'s Favorite Songs");
    }
   
    
    function dj($dj, $page = 1)
    {
        $tracks = $this->Track->findAll(array('Track.dj' => $dj), null, "`Post`.`date` DESC", 25, $page);
        $this->setPlaylist($tracks);
        
        $player = self::player($page);
        
        $artists = $this->Track->getPopularArtists();
        $djs = $this->Track->getPopularDJs();
        $this->set('artists', $artists);
        $this->set('djs', $djs);
        $this->set('page', $page);
        $this->set('tracks', $tracks);
        $this->set('player', $player);
        $this->set('title', 'Mixes by '.ucwords($artist));
        $this->render('latest');
    }
    
    
    function _getEmbeds($tracks)
    {
        foreach ($tracks as $i=>&$track)
        {
            $embed = $this->Embed->find(array("Embed.post_id" => $track['Track']['post_id']));
            $track['Embed']['src'] = $embed['Embed']['src'];
            //$track = $this->Track->format($track);
            
            $track['Track']['likes'] = $this->Like->getLikeCount($track['Track']['id']);
        }
        
        return $tracks;
    }
    
    function _getPhotos($tracks)
    {
        foreach ($tracks as $i=>&$track)
        {
            $photos = $this->Photo->findAll(array(
                "object_type" => "post", 
                "object_key" => $track['Track']['post_id']));
            
            foreach ($photos as $photo)
            {
                if ($photo['Photo']['width'] >= 100 && $photo['Photo']['height'] >= 199)
                {
                    $track['Photos'][] = $photo;
                }
            }
        }
        
        
        return $tracks;
    }
    
    function player($page)
    {
        $player = '<div id="flashcontent"></div><script type="text/javascript">
    		// <![CDATA[
    
    		var so = new SWFObject("/swf/ep/ep_player.swf", "ep_player", "240", "16", "9", "#009966");
    		so.addVariable("skin", "/swf/ep/skins/micro_player/skin.xml");
    		so.addVariable("playlist", "/post/playlist/'.$page.'");
    		so.addVariable("autoplay", "false");
    		so.addVariable("shuffle", "false");
    		so.addVariable("repeat", "false");
    		so.addVariable("buffertime", "1");
    		
    		// this parameter activates the use of event callbacks
    		// like MP3_PLAYING / MP3_PAUSED / MP3_STOPPED
    		so.addVariable("notifyonevent", "true");
    		
    		so.addParam("allowscriptaccess", "always");
    		so.write("flashcontent");
    
    		// ]]>
    	</script>';
    
    	return $player;	
	}
}

?>
